require('dotenv').config({ path: './config.env' });
const mysql = require('mysql2/promise');

async function tryConnection(password) {
  try {
    const connection = await mysql.createConnection({
      host: 'localhost',
      user: 'root',
      password: password,
      database: 'study_platform'
    });
    return connection;
  } catch (error) {
    return null;
  }
}

async function fixDatabaseIndexes() {
  // 尝试多个可能的密码
  const passwords = ['your_password', 'msblog123456', '', 'root', '123456'];
  let connection = null;
  
  for (const password of passwords) {
    console.log(`🔍 尝试密码: ${password || '(空密码)'}`);
    connection = await tryConnection(password);
    if (connection) {
      console.log(`✅ 连接成功，使用密码: ${password || '(空密码)'}`);
      break;
    }
  }
  
  if (!connection) {
    throw new Error('无法连接到数据库，请检查密码配置');
  }

  try {
    console.log('🔍 检查users表的索引...');
    
    // 查看当前索引
    const [indexes] = await connection.execute('SHOW INDEX FROM users');
    console.log(`当前索引数量: ${indexes.length}`);
    
    // 删除所有非主键索引
    const uniqueIndexes = [...new Set(indexes.filter(idx => idx.Key_name !== 'PRIMARY').map(idx => idx.Key_name))];
    
    for (const indexName of uniqueIndexes) {
      try {
        await connection.execute(`DROP INDEX \`${indexName}\` ON users`);
        console.log(`✅ 删除索引: ${indexName}`);
      } catch (error) {
        console.log(`⚠️ 删除索引失败 ${indexName}:`, error.message);
      }
    }
    
    // 重新创建必要的索引
    try {
      await connection.execute('CREATE UNIQUE INDEX idx_username ON users (username)');
      console.log('✅ 创建username唯一索引');
    } catch (error) {
      console.log('⚠️ 创建username索引失败:', error.message);
    }
    
    try {
      await connection.execute('CREATE UNIQUE INDEX idx_email ON users (email)');
      console.log('✅ 创建email唯一索引');
    } catch (error) {
      console.log('⚠️ 创建email索引失败:', error.message);
    }
    
    // 检查最终结果
    const [finalIndexes] = await connection.execute('SHOW INDEX FROM users');
    console.log(`✅ 修复完成，当前索引数量: ${finalIndexes.length}`);
    
  } catch (error) {
    console.error('❌ 修复失败:', error);
  } finally {
    await connection.end();
  }
}

fixDatabaseIndexes().then(() => {
  console.log('🎉 数据库索引修复完成');
  process.exit(0);
}).catch(error => {
  console.error('💥 修复过程出错:', error);
  process.exit(1);
}); 